<template>
  <el-dialog v-el-drag-dialog width="400px" title="上传图片" v-if="showDialog" :visible.sync="showDialog" append-to-body>
    <el-upload
      class="upload-demo"
      action=""
      drag
      multiple
      :auto-upload="true"
      :limit="limit"
      ref="upload"
      :show-file-list="true"
      :http-request="uploadImage"
      :before-remove="removeFile"
      :before-upload="beforeUpload"
      :file-list="fileList">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传{{limit}}张图片，且每张不超过{{size}}Mb</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="close">关闭</el-button>
      <el-button size="mini" type="primary" @click="save">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addImg } from '../../request/dataBase/customManage'
export default {
  name: 'uploadImage',
  props: {
    limit: {
      type: Number,
      default: 1 // 文件个数限制 默认一个
    },
    size: {
      type: Number,
      default: 5
    }
  },
  data () {
    return {
      showDialog: false,
      fileList: [],
      reg: /^(.*)(upload.*)$/
    }
  },
  methods: {
    // 上传前钩子
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > this.size) {
        this.$message.warning({
          message: '请控制文件不超过' + this.size + 'M'
        })
        return false
      }
      if (file.type.indexOf('image') === -1) {
        this.$message.error({
          message: '请上传正确的图片类型'
        })
        return false
      }
    },
    uploadImage (file) {
      addImg(file.file).then(res => {
        this.fileList.push({
          name: file.file.name,
          url: res.data.url.replace(this.reg, '$2')
        })
      })
    },
    removeFile (file, fileList) {
      this.fileList = fileList
    },
    save () {
      this.$emit('save', [...this.fileList])
      this.fileList = []
    },
    close () {
      this.showDialog = false
    },
    open () {
      this.showDialog = true
    }
  }
}
</script>